import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routers'
import VueCookie from 'vue-cookie'
import { ACCESS_TOKEN } from '@/store/mutation-types'

Vue.use(VueRouter)
const router = new VueRouter({
  routes,
  mode: 'history'
})

// 路由跳转 不带参数
Vue.prototype.$go = function(path) {
  this.$router.push({
    path: path
  })
}
// 路由跳转 带参
Vue.prototype.$goNewWithData = function(path, data) {
  const routeData = this.$router.resolve({
    name: path,
    query: {
      data: data
    }
  })
  window.open(routeData.href, '_blank')
}

// 路由替换 打开标签页
Vue.prototype.$goNew = function(path) {
  const routeData = this.$router.resolve({
    path: path
  })
  window.open(routeData.href, '_blank')
}

// 修复 反复点击同一路由时报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 全局前置守卫（回调函数）
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth === true) {
    const accessToken = VueCookie.get(ACCESS_TOKEN)
    if (accessToken !== undefined) {
      next()
    } else {
      router.push('/login')
    }
  } else {
    next()
  }
})

export default router
